<template>
  <div class="cloze-container">
    <!-- 页面标题 -->
    <header class="page-header">
      <div class="test-info">
        <span>总空数: 20 个</span>
        <span class="separator">|</span>
        <span>已完成: {{ completedCount }} 个</span>
        <span v-if="isSubmitted" class="separator">|</span>
        <span v-if="isSubmitted" class="score">得分: {{ score }} / 100</span>
      </div>
    </header>

    <!-- 左右布局容器 -->
    <div class="content-wrapper">
      <!-- 左侧：原文展示区 -->
      <div class="passage-container">
        <!-- 右上角按钮组 -->
        <div class="top-right-buttons">
          <button
              @click="increaseFontSize"
              class="action-btn edit" title="">
            <el-icon size="20"><ZoomIn /></el-icon>
          </button>
          <button
              @click="decreaseFontSize"
              class="action-btn delete" title="">
            <el-icon size="20"><ZoomOut /></el-icon>
          </button>
          <button
              @click="resetFontSize"
              class="action-btn setting" title="">
            <el-icon size="20"><Refresh /></el-icon>
          </button>
        </div>

        <h2>原文</h2>
        <div class="passage-content" :style="{ fontSize: currentSize + 'px' }">
          <p v-for="(paragraph, paraIndex) in splitPassage" :key="paraIndex">
            <template v-for="(item, itemIndex) in paragraph" :key="itemIndex">
              <!-- 普通文本 -->
              <span v-if="typeof item === 'string'" class="passage-text">{{ item }}</span>
              
              <!-- 填空位置 -->
              <span 
                v-else 
                class="blank"
                :class="{
                  'completed': item.userAnswer !== null,
                  'correct': isSubmitted && item.userAnswer === item.correctAnswer,
                  'incorrect': isSubmitted && item.userAnswer !== null && item.userAnswer !== item.correctAnswer
                }"
              >
                {{ isSubmitted ? (item.userAnswer === item.correctAnswer ? item.correctAnswer : item.blankNumber) : item.blankNumber }}
              </span>
            </template>
          </p>
        </div>
      </div>

      <!-- 右侧：题目选项区 -->
      <div class="questions-container">
        <h2>题目与选项</h2>
        <div class="questions-list">
          <div 
            v-for="(question, index) in questions" 
            :key="index" 
            class="question-item"
            :class="{
              'completed': question.userAnswer !== null,
              'correct': isSubmitted && question.userAnswer === question.correctAnswer,
              'incorrect': isSubmitted && question.userAnswer !== null && question.userAnswer !== question.correctAnswer
            }"
          >
            <div class="question-number">第 {{ index + 1 }} 空</div>
            
            <div class="options">
              <label 
                v-for="(option, optIndex) in question.options" 
                :key="optIndex"
                class="option"
                :class="{
                  'selected': question.userAnswer === optIndex,
                  'correct': isSubmitted && optIndex === question.correctAnswer,
                  'incorrect': isSubmitted && question.userAnswer === optIndex && optIndex !== question.correctAnswer
                }"
              >
                <input 
                  type="radio" 
                  name="question-{{ index }}"
                  :checked="question.userAnswer === optIndex"
                  @change="handleOptionSelect(index, optIndex)"
                  :disabled="isSubmitted"
                >
                <span class="option-letter">{{ String.fromCharCode(65 + optIndex) }}</span>
                <span class="option-text">{{ option }}</span>
              </label>
            </div>
            
            <!-- 解析（提交后显示） -->
            <div v-if="isSubmitted" class="explanation">
              <strong>解析：</strong>{{ question.explanation }}
            </div>
          </div>
        </div>
        
        <!-- 控制按钮 -->
        <div class="control-buttons">
          <button 
            @click="handleSubmit" 
            class="submit-btn"
            :disabled="isSubmitted || completedCount < 3"
          >
            提交答案
          </button>
          
          <button 
            @click="handleReset" 
            class="reset-btn"
            :disabled="isSubmitted || completedCount === 0"
          >
            重新开始
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import {Refresh, ZoomIn, ZoomOut} from "@element-plus/icons-vue";

// 完形填空原文（包含20个空）
const originalPassage = `
One day, a little boy named Tom was walking through the park when he saw a small bird that had fallen from {{ blank1 }} nest. The bird looked lost and {{ blank2 }}, so Tom decided to help it. He gently picked {{ blank3 }} up and looked around for its mother.
After searching for a while, Tom {{ blank4 }} not find the mother bird. He knew he couldn't leave the bird alone, so he decided to take it home. His mother helped him make a small box for the bird {{ blank5 }} a bed. They fed it small pieces of bread and gave it some water.
Every day, Tom would check on the bird and {{ blank6 }} it. He named the bird Charlie. As the days went by, Charlie started to get stronger. It would chirp when it saw Tom, as if it was saying hello. Tom was very {{ blank7 }} to see Charlie getting better.
One morning, Tom opened the box and Charlie flew out! Tom was sad at first, but then he saw Charlie flying around the garden. Charlie didn't fly away; {{ blank8 }} stayed nearby. Tom realized that Charlie wanted to be free but also wanted to stay close to him.
From that day on, Charlie would visit Tom every day. It would sit on Tom's shoulder while he {{ blank9 }} his homework or play in the garden. Tom learned that helping others can bring a lot of happiness. He also learned that {{ blank10 }} is important to be kind to all living things.
One afternoon, while Tom and Charlie were in the garden, they heard a noise. It was a cat! The cat was trying to catch Charlie. Tom quickly {{ blank11 }} Charlie in his hands and chased the cat away. Charlie was scared but safe. Tom knew he had to protect Charlie.
As the seasons changed, Charlie grew older. It started to bring small gifts to Tom, like shiny stones or feathers. Tom would keep these gifts in a special box. He felt very lucky to have such a {{ blank12 }} friend.
One day, Charlie didn't come to visit. Tom waited all day, but Charlie didn't appear. He was worried. The next day, Charlie came back, but this time it brought a friend - another bird! Tom was happy to see that Charlie had found a companion.
Over time, Charlie and its friend had babies. Tom would watch the baby birds grow up in their nest in the tree. He learned about the circle of life and how everything is {{ blank13 }}. He felt proud to have been part of Charlie's life.
Years later, Tom still remembered his friend Charlie. He often told stories about their adventures to his own children. He taught them to be kind to animals and to help those in need. Charlie had taught Tom an important lesson that he would never {{ blank14 }}.
The memory of Charlie stayed with Tom throughout his life. It reminded him that even small acts of kindness can make a big difference. And sometimes, the friendships we form with animals can be just as special as those we form with {{ blank15 }}.
One day, Tom's grandchildren asked him to tell them about Charlie. As he told the story, he noticed a small bird sitting on the windowsill. It looked just like Charlie. Tom smiled, wondering if it could be one of Charlie's descendants. Some friendships, he realized, truly do last {{ blank16 }}.
Tom's experience with Charlie taught him to appreciate the beauty of nature and the importance of compassion. He often walked through the same park where he had found Charlie, and every time he did, he would think about how that chance {{ blank17 }} had changed his life.
He started volunteering at a local animal shelter, helping to care for animals in need. He told everyone he met about Charlie and how one small bird had taught him so much about life, love, and friendship. People would often comment on what a kind and caring person Tom was, and he knew that it was all because of Charlie.
In the end, Tom lived a long and happy life, filled with many meaningful relationships - both with people and animals. He never forgot the lesson he had learned that day in the park: that kindness is a gift that keeps on {{ blank18 }}, and that every living creature deserves our respect and care.
And so, the story of Tom and Charlie lives on, a reminder to us all that even the smallest acts of kindness can create ripples that spread far and wide. It teaches us to be present, to notice those in need, and to act with compassion whenever we {{ blank19 }} the chance. For in doing so, we not only help others but also enrich our own lives in ways we could never have {{ blank20 }}.
`;

// 题目数据（20个空）
const questions = ref([
  {
    options: ["its", "it's", "their", "them"],
    correctAnswer: 0,
    explanation: "这里需要形容词性物主代词，指代小鸟的巢，所以用its。",
    userAnswer: null
  },
  {
    options: ["scare", "scared", "scaring", "scares"],
    correctAnswer: 1,
    explanation: "scared是形容词，意为'害怕的'，描述小鸟的状态。",
    userAnswer: null
  },
  {
    options: ["it", "its", "them", "they"],
    correctAnswer: 0,
    explanation: "it作为代词指代前面提到的小鸟（单数）。",
    userAnswer: null
  },
  {
    options: ["could", "can", "should", "would"],
    correctAnswer: 0,
    explanation: "讲述过去发生的事情，用can的过去式could。",
    userAnswer: null
  },
  {
    options: ["with", "has", "have", "by"],
    correctAnswer: 0,
    explanation: "with表示'带有'，这里指带有床的盒子。",
    userAnswer: null
  },
  {
    options: ["feed", "feeds", "fed", "feeding"],
    correctAnswer: 0,
    explanation: "would后接动词原形，与check并列。",
    userAnswer: null
  },
  {
    options: ["sad", "angry", "happy", "tired"],
    correctAnswer: 2,
    explanation: "看到小鸟好转，Tom应该是高兴的，所以用happy。",
    userAnswer: null
  },
  {
    options: ["he", "she", "it", "they"],
    correctAnswer: 2,
    explanation: "it指代小鸟Charlie（单数）。",
    userAnswer: null
  },
  {
    options: ["do", "does", "did", "doing"],
    correctAnswer: 3,
    explanation: "while引导的时间状语从句，用过去进行时。",
    userAnswer: null
  },
  {
    options: ["this", "that", "it", "what"],
    correctAnswer: 2,
    explanation: "it作为形式主语，真正的主语是后面的不定式短语。",
    userAnswer: null
  },
  {
    options: ["catch", "caught", "catches", "catching"],
    correctAnswer: 1,
    explanation: "描述过去发生的动作，用catch的过去式caught。",
    userAnswer: null
  },
  {
    options: ["faithful", "faithfully", "faith", "faiths"],
    correctAnswer: 0,
    explanation: "需要形容词修饰名词friend，faithful意为'忠诚的'。",
    userAnswer: null
  },
  {
    options: ["connect", "connected", "connecting", "connection"],
    correctAnswer: 1,
    explanation: "被动语态，be + 过去分词，意为'万物都是相互联系的'。",
    userAnswer: null
  },
  {
    options: ["forget", "forgot", "forgotten", "forgetting"],
    correctAnswer: 0,
    explanation: "would后接动词原形，never forget意为'永远不会忘记'。",
    userAnswer: null
  },
  {
    options: ["people", "person", "man", "men"],
    correctAnswer: 0,
    explanation: "people是复数形式，指'人们'，与animals对应。",
    userAnswer: null
  },
  {
    options: ["forever", "never", "seldom", "sometimes"],
    correctAnswer: 0,
    explanation: "forever意为'永远'，符合上下文语境。",
    userAnswer: null
  },
  {
    options: ["meeting", "meet", "met", "meets"],
    correctAnswer: 0,
    explanation: "chance meeting意为'偶然的相遇'，动名词作定语。",
    userAnswer: null
  },
  {
    options: ["give", "giving", "given", "gives"],
    correctAnswer: 1,
    explanation: "keep on doing sth. 表示'持续做某事'。",
    userAnswer: null
  },
  {
    options: ["has", "have", "had", "having"],
    correctAnswer: 1,
    explanation: "主语是we，一般现在时，用have。",
    userAnswer: null
  },
  {
    options: ["imagined", "imagine", "imagining", "imagines"],
    correctAnswer: 0,
    explanation: "过去完成时，had + 过去分词，意为'想象不到的方式'。",
    userAnswer: null
  }
]);

// 处理原文，将空白处替换为标记
const splitPassage = ref([]);

// 处理原文，拆分文本和空白
const processPassage = () => {
  // 按空白标记分割原文
  const parts = originalPassage.split(/\{\s*blank(\d+)\s*\}/g);
  // console.log(parts);
  const result = [];
  let paragraph = [];
  
  for (let i = 0; i < parts.length; i++) {
    // 偶数索引是文本部分
    if (i % 2 === 0) {
      const text = parts[i].trim();
      if (text) {
        // 按换行分割段落
        const textParts = text.split('\n');
        textParts.forEach((part, index) => {
          if (part) {
            paragraph.push(part);
          }
          // 最后一个部分不添加段落分割
          if (index < textParts.length - 1 && part) {
            result.push([...paragraph]);
            paragraph = [];
          }
        });
      }
    } 
    // 奇数索引是空白标记
    else {
      const blankNumber = parseInt(parts[i]);
      paragraph.push({
        type: 'blank',
        blankNumber,
        ...questions.value[blankNumber - 1]
      });
    }
  }
  
  // 添加最后一个段落
  if (paragraph.length > 0) {
    result.push(paragraph);
  }
  
  splitPassage.value = result;
};

// 初始化时处理原文
onMounted(() => {
  // console.log(completedCount.value)
  // console.log(completedCount.value === 0)
  processPassage();
});

// 状态管理
const isSubmitted = ref(false);

// 计算已完成题目数量
const completedCount = computed(() => {
  return questions.value.filter(q => q.userAnswer !== null).length;
});

// 计算得分
const score = computed(() => {
  const correctCount = questions.value.filter(q => q.userAnswer === q.correctAnswer).length;
  return Math.round((correctCount / questions.value.length) * 100);
});

// 选择选项
const handleOptionSelect = (questionIndex, optionIndex) => {
  if (!isSubmitted.value) {
    questions.value[questionIndex].userAnswer = optionIndex;
    // 更新原文显示
    processPassage();
  }
};

// 提交答案
const handleSubmit = () => {
  isSubmitted.value = true;
  processPassage();
};

// 重置答题
const handleReset = () => {
  questions.value.forEach(q => {
    q.userAnswer = null;
  });
  isSubmitted.value = false;
  processPassage();
};

// 字体大小相关配置
const baseSize = 16; // 默认基础字体大小
const minSize = 12;  // 最小字体大小
const maxSize = 28;  // 最大字体大小
const step = 2;      // 每次调整的步长

// 当前字体大小
const currentSize = ref(baseSize);

// 增大字体
const increaseFontSize = () => {
  if (currentSize.value < maxSize) {
    currentSize.value += step;
  }
};

// 减小字体
const decreaseFontSize = () => {
  if (currentSize.value > minSize) {
    currentSize.value -= step;
  }
};

// 重置字体大小
const resetFontSize = () => {
  currentSize.value = baseSize;
};
</script>

<style scoped>
.cloze-container {
  max-width: 1600px;
  margin: 0 auto;
  padding: 20px;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  color: #333;
  line-height: 1.8;
}

/* 头部样式 */
.page-header {
  padding: 20px;
  color: black;
  border-radius: 8px;
  margin-bottom: 10px;
}

.option-text{
  font-size: 12px;
}

.test-info {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  font-size: 14px;
}

.separator {
  color: #bbb;
}

.score {
  color: #4cd964;
  font-weight: 500;
}

/* 左右布局容器 */
.content-wrapper {
  display: flex;
  gap: 30px;
  height: calc(100vh - 180px);
}

/* 左侧原文区域 */
.passage-container {
  flex: 1;
  border: solid 1px #ddd;
  background-color: #fff;
  border-radius: 8px;
  padding: 25px;
  position: relative; /* 关键：父容器设为相对定位 */
  /* 隐藏滚动条但保留滚动功能 */
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE and Edge */
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
  overflow-y: auto;
}

.passage-container h2 {
  margin-top: 0;
  color: #2c3e50;
  border-bottom: 2px solid #3498db;
  padding-bottom: 10px;
}

.passage-content p {
  margin: 0 0 20px 0;
  text-align: justify;
}

.passage-text {
  white-space: pre-wrap;
}

.blank {
  display: inline-block;
  width: 60px;
  height: 28px;
  margin: 0 5px;
  text-align: center;
  line-height: 28px;
  border-bottom: 2px solid #3498db;
  font-weight: bold;
  color: #3498db;
  position: relative;
}

.blank.completed {
  border-color: #3498db;
}

.blank.correct {
  background-color: #dcfce7;
  border-color: #2ecc71;
  color: #2ecc71;
}

.blank.incorrect {
  background-color: #fee2e2;
  border-color: #e74c3c;
  color: #e74c3c;
}

/* 右侧题目区域 */
.questions-container {
  flex: 0 0 500px;
  border: solid 1px #ddd;
  background-color: #fff;
  border-radius: 8px;
  padding: 25px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
  display: flex;
  flex-direction: column;
}

.passage-container::-webkit-scrollbar {
  width: 1px; /* 滚动条宽度 */
}

.passage-container::-webkit-scrollbar-track {
  background: transparent; /* 透明轨道 */
}

.passage-container::-webkit-scrollbar-thumb {
  background-color: rgba(156, 163, 175, 0); /* 初始透明 */
  border-radius: 3px;
  transition: background-color 0.3s ease;
}

.questions-list::-webkit-scrollbar {
  width: 1px; /* 滚动条宽度 */
}

.questions-list::-webkit-scrollbar-track {
  background: transparent; /* 透明轨道 */
}

.questions-list::-webkit-scrollbar-thumb {
  background-color: rgba(156, 163, 175, 0); /* 初始透明 */
  border-radius: 3px;
  transition: background-color 0.3s ease;
}

.questions-container h2 {
  margin-top: 0;
  color: #2c3e50;
  border-bottom: 2px solid #3498db;
  padding-bottom: 10px;
}

.questions-list {
  flex: 1;
  overflow-y: auto;
  margin-bottom: 10px;
  /* 隐藏滚动条但保留滚动功能 */
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE and Edge */
}

.question-item {
  padding: 5px;
  border-radius: 6px;
  margin-bottom: 15px;
  background-color: #f8fafc;
  border-left: 4px solid transparent;
  transition: all 0.3s ease;
}

.question-item.completed {
  border-left-color: #3498db;
}

.question-item.correct {
  border-left-color: #2ecc71;
  background-color: #f0fff4;
}

.question-item.incorrect {
  border-left-color: #e74c3c;
  background-color: #fff5f5;
}

.question-number {
  font-weight: bold;
  margin-bottom: 10px;
  color: #2c3e50;
}

.options {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

/* 右上角按钮组 */
.top-right-buttons {
  position: absolute; /* 绝对定位，相对于父容器 */
  top: 10px;          /* 距离顶部10px */
  right: 10px;        /* 距离右侧10px */
  display: flex;      /* 按钮横向排列 */
  gap: 8px;           /* 按钮之间的间距 */
}

/* 按钮样式 */
.action-btn {
  width: 32px;
  height: 32px;
  border: none;
  border-radius: 4px;
  background: #f5f5f5;
  color: #666;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
}

.action-btn:hover {
  background: #e0e0e0;
  color: #333;
}

.action-btn.edit:hover {
  background: #e6f7ff;
  color: #1890ff;
}

.action-btn.delete:hover {
  background: #fff2f0;
  color: #f5222d;
}

.action-btn.setting:hover {
  background: #fffbe6;
  color: #faad14;
}

.option {
  display: flex;
  align-items: center;
  padding: 5px 10px;
  background-color: white;
  border: 1px solid #e2e8f0;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.option:hover:not(:has(input:disabled)) {
  background-color: #eff6ff;
  border-color: #93c5fd;
}

.option input {
  margin-right: 12px;
  width: 16px;
  height: 16px;
}

.option-letter {
  display: inline-flex;
  justify-content: center;
  align-items: center;
  width: 24px;
  height: 24px;
  background-color: #e9ecef;
  color: #495057;
  border-radius: 4px;
  margin-right: 12px;
  font-weight: 600;
}

.option.selected {
  background-color: #dbeafe;
  border-color: #3b82f6;
}

.option.selected .option-letter {
  background-color: #3b82f6;
  color: white;
}

.option.correct {
  background-color: #dcfce7;
  border-color: #2ecc71;
}

.option.correct .option-letter {
  background-color: #2ecc71;
  color: white;
}

.option.incorrect {
  background-color: #fee2e2;
  border-color: #ef4444;
}

.option.incorrect .option-letter {
  background-color: #ef4444;
  color: white;
}

.explanation {
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px dashed #e2e8f0;
  font-size: 14px;
  color: #4b5563;
}

/* 按钮样式 */
.control-buttons {
  display: flex;
  gap: 15px;
}

.submit-btn, .reset-btn {
  flex: 1;
  padding: 12px;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.25s ease;
}

.submit-btn {
  background-color: #3498db;
  color: white;
}

.submit-btn:hover:not(:disabled) {
  background-color: #2980b9;
  box-shadow: 0 4px 8px rgba(52, 152, 219, 0.3);
}

.submit-btn:disabled {
  background-color: #a0c4e7;
  cursor: not-allowed;
}

.reset-btn {
  background-color: #f1f3f5;
  color: #495057;
}

.reset-btn:disabled {
  background-color: #a0c4e7;
  cursor: not-allowed;
}

.reset-btn:hover {
  background-color: #a0c4e7;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .content-wrapper {
    flex-direction: column;
    height: auto;
  }
  
  .questions-container {
    flex: none;
    width: 100%;
  }
}
</style>